<template>
    <div>
        <div>
            <a-form style="margin-top: 10px;margin-left: 5px;" :layout="'inline'">
                <a-form-item label="活动名称">
                    <a-input v-model:value="searchParams.name" placeholder="请输入活动名称" allowClear/>
                </a-form-item>
                <a-form-item label="活动介绍">
                    <a-input v-model:value="searchParams.introduction" placeholder="请输入活动介绍" allowClear/>
                </a-form-item>
                <a-form-item label="发布者">
                    <a-input v-model:value="searchParams.publisher" placeholder="请输入发布者" allowClear/>
                </a-form-item>
                <a-form-item label="是否下线">
                    <a-select
                            ref="select"
                            v-model:value="searchParams.status"
                            placeholder="请选择是否下线"
                            style="width: 150px"
                            allowClear
                    >
                        <a-select-option value="0">否</a-select-option>
                        <a-select-option value="1">是</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item>
                    <a-button @click="search" type="primary">
                        <template #icon>
                            <SearchOutlined/>
                        </template>
                        搜索
                    </a-button>
                    <a-button @click="resetSearch" class="main_rest">
                        <template #icon>
                            <SyncOutlined/>
                        </template>
                        重置
                    </a-button>
                </a-form-item>
            </a-form>
            <div class="main_operation">
                <a-button @click="handleAdd" class="main_operation_item" type="primary">
                    新增
                    <template #icon>
                        <PlusOutlined/>
                    </template>
                </a-button>
                <a-button @click="handleEdit" :disabled="single" class="main_operation_edit">
                    <template #icon>
                        <EditTwoTone/>
                    </template>
                    修改
                </a-button>
                <a-button @click="handleDelete" :disabled="multiple" class="main_operation_item" type="primary" danger>
                    <template #icon>
                        <DeleteTwoTone/>
                    </template>
                    删除
                </a-button>
                <a-button @click="handleExportProblem" class="main_operation_export">
                    <template #icon>
                        <VerticalAlignBottomOutlined/>
                    </template>
                    导出
                </a-button>
            </div>
        </div>

        <a-table :row-selection="rowSelection" :columns="columns" :data-source="activityList" :pagination="pagination"
                 row-key="id" style="word-break: break-all;">
            <template v-slot:bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'image'">
                    <a-image :src="record.image" style="width: 130px;height: 130px" alt="头像"/>
                </template>
                <template v-if="column.dataIndex === 'voucher'">
                    <a-button @click="viewVoucher(record.id,record.name)" style="background-color: lightblue;">查看
                    </a-button>
                </template>
                <template v-if="column.dataIndex === 'operation'">
                    <div>
          <span>
            <a-button @click="handleEdit(record.id)" class="main_operation_button" type="primary" ghost>修改</a-button>
            <a-button v-if="record.status===0" @click="handleDelete(record)" class="main_operation_button"
                      type="primary">下线</a-button>
            <a-button v-else danger>已下线</a-button>
          </span>
                    </div>
                </template>
            </template>
        </a-table>

        <!-- 新增或修改对话框 -->
        <a-modal
                ref="modalRef"
                v-model:visible="visible"
                @ok="handleOk"
                cancelText="取消"
                okText="确认"
        >
            <a-form :label-col="{ span: 4 }">
                <a-form-item label="活动名称" v-bind="validateInfos.name">
                    <a-input v-model:value="activity.name" placeholder="请输入活动名称"/>
                </a-form-item>
                <a-form-item label="活动介绍" v-bind="validateInfos.introduction">
                    <a-textarea v-model:value="activity.introduction" :auto-size="{ minRows: 2, maxRows: 7 }"
                                placeholder="请输入活动介绍"/>
                </a-form-item>
                <a-form-item label="价格" v-bind="validateInfos.price">
                    <a-input v-model:value="activity.price" placeholder="请输入价格"/>
                </a-form-item>
                <a-form-item label="发布者" v-bind="validateInfos.publisher">
                    <a-input v-model:value="activity.publisher" placeholder="请输入发布者" disabled/>
                </a-form-item>
                <a-form-item label="活动图片" v-bind="validateInfos.image">
                    <a-upload
                            class="avatar-uploader"
                            :show-upload-list="false"
                            :headers="headers"
                            :action="url"
                            :before-upload="beforeUpload"
                            @change="handleChange"
                    >
                        <img v-if="activity.image" :src="activity.image"
                             style="width: 150px;height: 150px;object-fit: cover;"
                             alt="avatar"/>
                        <div v-else>
                            <loading-outlined v-if="loading"></loading-outlined>
                            <plus-outlined v-else
                                           style="padding: 40px 50px 0;color: #666;font-size: 32px;"></plus-outlined>
                            <div class="ant-upload-text" style="margin-left: 40px;color: #666;">Upload</div>
                        </div>
                    </a-upload>
                </a-form-item>
                <a-form-item label="开始时间" v-bind="validateInfos.startTime">
                    <a-space direction="vertical">
                        <a-date-picker v-model:value="activity.startTime" valueFormat="YYYY-MM-DD HH:mm:ss"/>
                    </a-space>
                </a-form-item>
                <a-form-item label="结束时间" v-bind="validateInfos.endTime">
                    <a-date-picker v-model:value="activity.endTime" valueFormat="YYYY-MM-DD HH:mm:ss"/>
                </a-form-item>
                <a-form-item label="是否下线" v-bind="validateInfos.status">
                    <a-radio-group v-model:value="activity.status">
                        <a-radio :value="0">否</a-radio>
                        <a-radio :value="1">是</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-form>
            <template #title>
                <div ref="modalTitleRef" style="width: 100%; cursor: move">{{ title }}</div>
            </template>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import {
    addActivity,
    deleteActivity, exportActivity,
    getActivity,
    getActivityList,
    searchActivity,
    updateActivity
} from "@/api/activity/activity";
import {
    PlusOutlined,
    EditTwoTone,
    DeleteTwoTone,
    VerticalAlignBottomOutlined,
    SyncOutlined,
    SearchOutlined,
    FireTwoTone,
    LoadingOutlined
} from '@ant-design/icons-vue';
import {createVNode, reactive, ref} from "vue";
import {Form, message, TableColumnType, Modal, UploadChangeParam, UploadProps} from "ant-design-vue";
// @ts-ignore
import cookie from "js-cookie";
import {useRouter} from "vue-router";

const router = useRouter()

//查看优惠券
const viewVoucher = (id: number, name: string) => {
    router.push(`/voucher/${id}/${name}`)
}

//图片上传的地址
const url = ref<string>()
//活动图片
const image = ref<string>()
const loading = ref<boolean>(false);

//设置请求头
const headers = ref({
    "token": cookie.get("sysToken")
})

function getBase64(img: Blob, callback: (base64Url: string) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
}

const handleChange = (info: UploadChangeParam) => {
    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, () => {
            activity.value.image = info.file.response.data.url;
            loading.value = false;
        });
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};

//上传文件之前执行
const beforeUpload = (file: UploadProps['fileList'][number]) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

interface DataType {
    key: string;
    id: number;
}

//标签
const columns: TableColumnType<DataType>[] = [
    {
        title: '活动名称',
        align: "center",
        width: 100,
        dataIndex: 'name',
    },
    {
        title: '活动介绍',
        align: "center",
        width: 200,
        dataIndex: 'introduction',
    },
    {
        title: '价格(单位:分)',
        align: "center",
        dataIndex: 'price',
    },
    {
        title: '发布者',
        align: "center",
        width: 80,
        dataIndex: 'publisher',
    },
    {
        title: '活动图片',
        align: "center",
        width: 150,
        dataIndex: 'image',
    },
    {
        title: '开始时间',
        align: "center",
        width: 180,
        dataIndex: 'startTime',
    },
    {
        title: '结束时间',
        align: "center",
        width: 180,
        dataIndex: 'endTime',
    },
    {
        title: '是否下线',
        align: "center",
        dataIndex: 'status',
        customRender: (text: any) => {
            return text.value === 0 ? '否' : '是';
        }
    },
    {
        title: '优惠券',
        align: "center",
        dataIndex: 'voucher',
    },
    {
        title: '操作',
        align: "center",
        dataIndex: 'operation',
    },
];

//选中的id数组
const ids = ref<number[]>([])
//非单个禁用
const single = ref<boolean>(true)
//是否多选
const multiple = ref<boolean>(true)

//多选框
const rowSelection = {
    onChange: (selectedRowKeys: string[], selectedRows: DataType[]) => {
        ids.value = selectedRows.map(item => item.id)
        single.value = ids.value.length !== 1
        multiple.value = !ids.value.length
    }
};

//是否显示修改对话框
const visible = ref<boolean>(false);
//对话框标题
const title = ref("")

//活动信息
const activity = ref({
    id: '',
    name: '',
    introduction: '',
    publisher: '',
    price: '',
    image: '',
    startTime: '',
    endTime: '',
    status: ''
})

//表单校验
const rulesRef = reactive({
    name: [
        {
            required: true,
            message: '活动名称不能为空',
        }
    ],
    introduction: [
        {
            required: true,
            message: '活动介绍不能为空',
        }
    ],
    price: [
        {
            required: true,
            message: '价格不能为空',
        }
    ],
    publisher: [
        {
            required: true,
            message: '发布者不能为空',
        }
    ],
    image: [
        {
            required: true,
            message: '活动图片不能为空',
        }
    ],
    startTime: [
        {
            required: true,
            message: '开始时间不能为空',
        }
    ],
    endTime: [
        {
            required: true,
            message: '结束时间不能为空',
        }
    ],
    status: [
        {
            required: true,
            message: '状态不能为空',
        }
    ],
});

const useForm = Form.useForm;
const {validate, validateInfos} = useForm(activity, rulesRef);

//活动列表
const activityList = ref()

//分页参数
const pagination = ref({
    size: 'large',
    current: 1,
    pageSize: 10,
    total: 0,
    pageSizeOptions: ['10', '20', '30'],
    showTotal: (total: number) => {
        return " 共" + total + "条"
    },
    showSizeChanger: true,
    onShowSizeChange: (current: number, pageSize: number) => {
        pagination.value.pageSize = pageSize
        search()
    },
    onChange: (current: number) => {
        pagination.value.current = current
        search()
    }
})

//搜索参数
const searchParams = ref({
    name: '',
    introduction: '',
    publisher: '',
    status: null
})

//获取活动列表
const handleActivityList = () => {
    getActivityList(pagination.value.current, pagination.value.pageSize).then((res) => {
        activityList.value = res.data.data.map.list
        pagination.value.total = res.data.data.map.total
    })
}

//修改活动
const handleEdit = (id: number) => {
    reset()
    const activityId: any = ids.value[0] || id
    url.value = import.meta.env.VITE_BASE_URL + '/thirdParty/oss/uploadImgToActivity/' + activityId
    visible.value = true
    title.value = "修改活动信息"
    getActivity(activityId).then((res) => {
        activity.value = res.data.data.activity
    })
}

//新增活动
const handleAdd = () => {
    reset()
    url.value = import.meta.env.VITE_BASE_URL + '/thirdParty/oss/uploadImgToActivity/' + 0
    title.value = "新增活动信息"
    visible.value = true
    activity.value.publisher = JSON.parse(cookie.get('sysUser')).username
}

//删除活动
const handleDelete = (row: any) => {
    const activityIds: any = row.id || ids.value
    Modal.confirm({
        title: '你确定要下线活动吗?',
        icon: createVNode(FireTwoTone),
        okText: '确认',
        cancelText: '取消',
        onOk() {
            return new Promise((resolve, reject) => {
                setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                deleteActivity(activityIds).then(() => {
                    message.success("下线成功")
                    handleActivityList()
                })
            }).catch(() => console.log('Oops errors!'));
        },
        onCancel() {
        },
    });
}

//新增或修改提交按钮
const handleOk = () => {
    validate().then(() => {
        if (activity.value.id != '') {
            updateActivity(activity.value).then((res) => {
                if (res.data.code === 400) {
                    message.warn(res.data.message)
                } else {
                    visible.value = false;
                    handleActivityList()
                }
            })
        } else {
            addActivity(activity.value).then((res) => {
                if (res.data.code === 400) {
                    message.warn(res.data.message)
                } else {
                    visible.value = false;
                    handleActivityList()
                }
            })
        }
    }).catch(err => {
        console.log('error', err);
    });
}

//对话框表单重置
const reset = () => {
    activity.value.id = ''
    activity.value.name = ''
    activity.value.introduction = ''
    activity.value.price = ''
    activity.value.publisher = ''
    activity.value.image = ''
    activity.value.startTime = ''
    activity.value.endTime = ''
    activity.value.status = ''
}

//搜索表单重置
const resetSearch = () => {
    searchParams.value.name = ''
    searchParams.value.introduction = ''
    searchParams.value.publisher = ''
    searchParams.value.status = null
    handleActivityList()
}

//搜索
const search = () => {
    searchActivity(searchParams.value).then((res) => {
        activityList.value = res.data.data.list
        pagination.value.total = res.data.data.list.length
    })
}

//导出
const handleExportProblem = () => {
    exportActivity().then((response) => {
        message.success("导出成功")
        let blob = new Blob([response.data], {
            //要与后端对应
            type: 'application/vnd.ms-excel'
        });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '活动列表.xlsx';
        link.click();
        //释放内存
        window.URL.revokeObjectURL(link.href)
    })
}

handleActivityList()
</script>

<style lang="less" scoped>
.main_operation {
  margin: 10px;
  display: flex;

  .main_operation_item {
    margin-right: 10px;
  }

  .main_operation_edit {
    background-color: palegreen;
    margin-right: 10px;
  }

  .main_operation_export {
    background-color: sandybrown;
    margin-right: 10px;
  }
}

.main_rest {
  margin-left: 5px;
}

.main_operation_button {
  margin: 5px;
}

:deep(.ant-upload) {
  width: 128px;
  height: 128px;
}

:deep(.ant-form-item-control-input-content) {
  margin-bottom: 5px;
}
</style>